/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package listener;

import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author nivri
 */
public class FilterUsers implements Filter , Serializable {

    FilterConfig fc;
    private HashMap<String, String> map = new HashMap<String, String>();

    public HashMap<String, String> getMap() {
        return map;
    }

    public void setMap(HashMap<String, String> map) {
        this.map = map;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        fc = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        
        HttpServletRequest rq = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession sesion = rq.getSession(true);
        String pagereqest = rq.getRequestURL().toString();

        sesion.setAttribute("id", sesion.getId());

        chain.doFilter(request, response);

        if (pagereqest.substring(pagereqest.lastIndexOf("/")).equals("/login.xhtml")) {
            if (sesion.getAttribute("username") != null) {
                map = (HashMap<String, String>) sesion.getAttribute("HashMap");
                if (map.containsValue(sesion.getAttribute("username").toString())) {
                    Iterator it = map.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry e = (Map.Entry) it.next();

                        if (e.getValue().equals(sesion.getAttribute("username").toString())) {

                            if (!e.getKey().toString().equals(sesion.getId())) {
                                resp.sendRedirect("login.xhtml");

                            }
                        }

                    }


                }

                resp.sendRedirect("index.xhtml");

            }
        } else {

            if (sesion.getAttribute("username") == null) {
                map = (HashMap<String, String>) sesion.getAttribute("HashMap");
                resp.sendRedirect("login.xhtml");
            }
        }



    }

    @Override
    public void destroy() {
    }
}
